<template>
  <page-container>
    <a-card>
      <div class="form">
        <a-form
          :model="form"
          ref="formRef"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item label="流转单ID">{{ formState.id }}</a-form-item>
          <a-form-item label="原流转单标题">{{ formState.title }}</a-form-item>
          <a-form-item label="回复人">{{ formState.basicPerson }}</a-form-item>
          <a-form-item label="推送类别">{{ formState.type }}</a-form-item>
          <a-form-item label="审批领导">{{ formState.approvePerson }}</a-form-item>
          <a-form-item label="处理期限">
            {{ formState.handleStartTime }} 至 {{ formState.handleEndTime }}
          </a-form-item>
          <a-form-item label="推送情况" :span="24" :wrapper-col="{ span: 18 }">
            <span v-html="formState.basicContent"></span>
          </a-form-item>
          <a-form-item label="下发附件" name="basicContent" v-if="fileList.length">
            <a-upload :file-list="fileList" :multiple="true" name="file" disabled></a-upload>
          </a-form-item>
          <a-form-item label="回复内容" name="feedbackContent">
            <a-textarea
              v-model:value="form.feedbackContent"
              placeholder="请输入回复内容"
              style="min-height: 200px"
            />
          </a-form-item>
          <a-form-item label="回访单附件" name="file" v-if="isReturn">
            <a-upload
              :file-list="visitFileList"
              :multiple="true"
              name="file"
              @change="handlevisitChange"
              :before-upload="beforeUpload"
              accept="image/png, image/jpeg,image/tiff,image/bmp,image/gif,image/pcx"
            >
              <a-button type="dashed" v-if="!visitFileList.length">
                <upload-outlined></upload-outlined>
                +上传附件
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item label="反馈附件">
            <a-upload
              :file-list="feedbackFileList"
              :multiple="true"
              name="file"
              @change="handlefeedbackFileChange"
              :before-upload="beforefeedbackFileUpload"
            >
              <a-button type="dashed">
                <upload-outlined></upload-outlined>
                +上传附件
              </a-button>
            </a-upload>
          </a-form-item>
          <!-- <a-form-item label="回访记录" v-show="formState.type == 1 ? true : false">
            <a-button type="dashed" @click="handleEdit" v-show="isShow">编辑回访记录单</a-button>
            <a
              href="javascript:;"
              @click="handleEdit"
              style="text-decoration: underline"
              v-show="!isShow"
            >
              案件回访记录
            </a>
            <a-popconfirm
              v-if="!isShow"
              placement="topRight"
              ok-text="是"
              cancel-text="否"
              @confirm="handleDel"
            >
              <template v-slot:title>
                <p>你确定要删除吗?</p>
              </template>
            </a-popconfirm>
          </a-form-item> -->
        </a-form>
      </div>
      <div class="bottomc">
        <div class="buttonContent">
          <a-button @click="handleBack">取消</a-button>
          <a-button @click="readClick(parseInt(formState.status))" style="margin-left: 10px">
            PDF预览
          </a-button>
          <a-button type="primary" style="margin-left: 10px" @click="handleQD" :loading="loading">
            保存反馈
          </a-button>
          <a-button type="primary" style="margin-left: 10px" @click="handleFk" :loading="loading">
            提交反馈
          </a-button>
        </div>
      </div>
    </a-card>
    <!-- <modal ref="modalRef" @handleChange="ishandlegetRetuenDetail" /> -->
  </page-container>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onMounted, onActivated } from 'vue';
import type { UnwrapRef } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
// import modal from './components/modal.vue';
import { detail, feedbackUpdate, ProcessTypeTree } from '@/api/smart-tools/index';
import { getRetuenDelete, queryApproveLeader } from '@/api/smart-tools/index';
interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: string;
  url?: string;
  preview?: string;
  originFileObj?: any;
  file: Blob;
}
interface form {
  feedbackContent: string;
  file: string;
}
export default defineComponent({
  components: {},
  setup() {
    const fileList = ref<any>([]);
    const visitFileList = ref<any>([]);
    const feedbackFileList = ref<any>([]);
    const isReturn = ref<boolean>(false);
    const url = (window as any).g.baseURL + '/processBasic/preview';
    const rules = {
      feedbackContent: [{ required: true, message: '请输入...', trigger: 'blur' }],
      file: [{ required: true, message: '请上传...', trigger: 'change' }],
    };
    const form: UnwrapRef<form> = reactive({
      feedbackContent: '',
      file: '',
    });
    let formState = ref<any>({});
    const router = useRouter();
    //筛选审批领导
    const approvePersonList = ref<any>([]);
    const getApprovePerson = value => {
      let name = '';
      approvePersonList.value.filter(item => {
        if (item.userId == value) {
          name = item.userName;
        }
      });
      return name;
    };
    //存放未修改的回访单
    const pdfFile = ref<string>('');
    //存放未修改的反馈附件
    const pdfFileFeedback = ref<Array<string>>([]);
    const queryProcessBasicList = value => {
      detail(value).then(res => {
        formState.value = res.data[0];
        if (formState.value.basicContent.indexOf('\n') >= 0) {
          formState.value.basicContent = formState.value.basicContent.replace(/\n/g, '<br>');
        }
        form.feedbackContent = formState.value.feedbackContent;
        // if (formState.value.approveUserId) {
        //   formState.value.approveUserId = getApprovePerson(formState.value.approveUserId);
        // }
        if (formState.value.type) {
          type.value = formState.value.type;
          let newType = formState.value.type.split(',');
          if (newType[1] === '11') {
            isReturn.value = true;
          } else {
            isReturn.value = false;
          }
          typeList.value.filter(item => {
            if (item.code == newType[0]) {
              formState.value.type = item.name;
              item.children.filter(el => {
                if (el.code == newType[1]) {
                  formState.value.type = formState.value.type + '-' + el.name;
                }
              });
            }
          });
        }
        if (
          formState.value.pdfFileFeedback !== '' &&
          formState.value.pdfFileFeedback?.indexOf('|')
        ) {
          let fileArr = formState.value.pdfFileFeedback.split('|');
          fileArr.forEach((item: any, index) => {
            pdfFileFeedback.value.push(index);
            feedbackFileList.value.push({
              name: item,
              uid: index,
              status: 'done',
              response: 'Server Error 500', // custom error message to show
              url:
                (window as any).g.baseURL +
                '/processReturn/download' +
                '?fileName=' +
                item +
                '&processBasicId=' +
                router.currentRoute.value.query.id,
            });
          });
        }
        if (formState.value.basicFile !== '' && formState.value.basicFile?.indexOf('|')) {
          let fileArr = formState.value.basicFile.split('|');
          fileArr.forEach((item: any, index) => {
            fileList.value.push({
              name: item,
              uid: index,
              status: 'done',
              response: 'Server Error 500', // custom error message to show
              url:
                (window as any).g.baseURL +
                '/processReturn/download' +
                '?fileName=' +
                item +
                '&processBasicId=' +
                router.currentRoute.value.query.id,
            });
          });
        }
        if (formState.value.pdfFile) {
          pdfFile.value = formState.value.pdfFile;
          form.file = 'a';
          visitFileList.value = [
            {
              name: formState.value.pdfFile,
              uid: 1,
              status: 'done',
              response: 'Server Error 500', // custom error message to show
              url:
                (window as any).g.baseURL +
                '/processReturn/download' +
                '?fileName=' +
                formState.value.pdfFile +
                '&processBasicId=' +
                router.currentRoute.value.query.id,
            },
          ];
        }
      });
    };
    const formRef = ref();
    const loading = ref<boolean>(false);
    //反馈
    const type = ref<string>('');
    const handleFk = () => {
      let obj = {
        id: router.currentRoute.value.query.id,
        feedbackContent: form.feedbackContent,
        status: '3',
        type: type.value,
        pdfFile: pdfFile.value,
        pdfFileFeedback: pdfFileFeedback.value,
      };
      formRef.value
        .validate()
        .then(() => {
          const formData = new FormData();
          visitFileList.value.forEach((file: FileItem) => {
            formData.append('file', file.originFileObj);
          });
          let newPdfFileFeedback: any = [];
          feedbackFileList.value.forEach((file: FileItem) => {
            if (pdfFileFeedback.value.indexOf(file.uid as string) > -1) {
              newPdfFileFeedback.push(file.name);
            }
            if (file.originFileObj) {
              formData.append('feedbackFile', file.originFileObj);
            }
          });
          obj.pdfFileFeedback = newPdfFileFeedback.join('|');
          Object.keys(obj).forEach(key => {
            formData.append(key, obj[key]);
          });
          feedbackUpdate(formData)
            .then(res => {
              if (res.code === 200) {
                message.success('反馈成功!');
                router.back();
                loading.value = false;
              }
            })
            .finally(() => {
              loading.value = false;
            });
        })
        .catch(error => {
          loading.value = false;
          console.log('error', error);
        });
    };
    //确定
    const handleQD = () => {
      let obj = {
        id: router.currentRoute.value.query.id,
        feedbackContent: form.feedbackContent,
        type: type.value,
        pdfFile: pdfFile.value,
        pdfFileFeedback: pdfFileFeedback.value,
        operation: 0,
      };
      formRef.value
        .validate()
        .then(() => {
          const formData = new FormData();
          visitFileList.value.forEach((file: FileItem) => {
            if (file.originFileObj) {
              formData.append('file', file.originFileObj);
              obj.pdfFile = '';
            }
          });
          let newPdfFileFeedback: any = [];
          feedbackFileList.value.forEach((file: FileItem) => {
            if (pdfFileFeedback.value.indexOf(file.uid as string) > -1) {
              newPdfFileFeedback.push(file.name);
            }
            if (file.originFileObj) {
              formData.append('feedbackFile', file.originFileObj);
            }
          });
          obj.pdfFileFeedback = newPdfFileFeedback.join('|');
          Object.keys(obj).forEach(key => {
            formData.append(key, obj[key]);
          });
          feedbackUpdate(formData)
            .then(res => {
              if (res.code === 200) {
                message.success('保存成功!');
                router.back();
                loading.value = false;
              }
            })
            .finally(() => {
              loading.value = false;
            });
        })
        .catch(error => {
          loading.value = false;
          console.log('error', error);
        });
    };
    //取消
    const handleBack = () => {
      router.back();
    };
    const handleDel = () => {
      getRetuenDelete({
        processBasicId: router.currentRoute.value.query.id,
      }).then(res => {
        if (res.code == '200') {
          message.success('删除成功!');
        }
      });
    };
    //PDF阅览
    const readClick = (type: number) => {
      window.open(url + '?type=' + type + '&processBasicId=' + router.currentRoute.value.query.id);
    };
    //推送类别数据
    const typeList = ref<any>([]);
    const handleProcessTypeTree = () => {
      ProcessTypeTree().then(res => {
        typeList.value = res.data;
      });
    };
    //回访单附件
    const handlevisitChange = info => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-2);
      resFileList = resFileList.map(file => {
        if (file.response) {
          file.url = file.response.url;
        }
        return file;
      });
      visitFileList.value = resFileList;
      if (resFileList.length) {
        form.file = 'a';
      } else {
        form.file = '';
      }
    };
    const beforeUpload = (file: FileItem) => {
      visitFileList.value = [...fileList.value, file];
      form.file = 'a';
      return false;
    };
    //反馈附件
    const handlefeedbackFileChange = info => {
      let resFileList = [...info.fileList];
      //   resFileList = resFileList.slice(-2);
      let newList: any = [];
      resFileList = resFileList.map(file => {
        newList.push(file.name);
        if (file.response) {
          file.url = file.response.url;
        }
        return file;
      });
      feedbackFileList.value = resFileList;
    };
    const beforefeedbackFileUpload = (file: FileItem) => {
      feedbackFileList.value = [...fileList.value, file];
      return false;
    };
    const handlequeryApproveLeader = () => {
      queryApproveLeader().then(res => {
        approvePersonList.value = res.data;
      });
    };
    onMounted(() => {
      handlequeryApproveLeader();
    });
    onActivated(() => {
      handleProcessTypeTree();
      feedbackFileList.value = [];
      fileList.value = [];
      queryProcessBasicList({ id: router.currentRoute.value.query.id });
    });
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      handleProcessTypeTree,
      handlequeryApproveLeader,
      formState,
      router,
      handleFk,
      form,
      handleBack,
      rules,
      formRef,
      loading,
      handleDel,
      readClick,
      fileList,
      visitFileList,
      handlevisitChange,
      beforeUpload,
      feedbackFileList,
      handlefeedbackFileChange,
      beforefeedbackFileUpload,
      isReturn,
      type,
      getApprovePerson,
      handleQD,
      pdfFile,
      pdfFileFeedback,
      typeList,
    };
  },
});
</script>
<style lang="less" scoped>
.form {
  width: 50%;
  margin: 0 auto;
  padding: 30px;
  :deep(.ant-form-horizontal .ant-form-item-control) {
    padding-top: 0px;
  }
}
.bottomc {
  display: flex;
  align-items: center;
  width: 100%;
  height: 70px;
  border-top: 1px solid #3f424d;
  .buttonContent {
    width: 400px;
    margin: 0 auto;
  }
}
:deep(.ant-card-body) {
  padding: 0;
}
:deep(.ant-btn-dashed) {
  color: rgba(32, 94, 233, 1);
  border-color: rgba(32, 94, 233, 1);
}
</style>
